-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathconfig.rs
1735 lines (1611 loc) · 59.3 KB
/
config.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
pub use crate::protocol::types::Server;
use crate::{
error::{Error, ErrorKind},
protocol::command::Command,
types::{ClusterHash, RespVersion},
utils,
};
use socket2::TcpKeepalive;
use std::{cmp, fmt::Debug, time::Duration};
use url::Url;
#[cfg(feature = "mocks")]
use crate::mocks::Mocks;
#[cfg(feature = "credential-provider")]
use async_trait::async_trait;
#[cfg(feature = "unix-sockets")]
use std::path::PathBuf;
#[cfg(any(feature = "mocks", feature = "credential-provider"))]
use std::sync::Arc;
#[cfg(any(
feature = "enable-rustls",
feature = "enable-native-tls",
feature = "enable-rustls-ring"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(
feature = "enable-rustls",
feature = "enable-native-tls",
feature = "enable-rustls-ring"
)))
)]
pub use crate::protocol::tls::{HostMapping, TlsConfig, TlsConnector, TlsHostMapping};
#[cfg(feature = "replicas")]
#[cfg_attr(docsrs, doc(cfg(feature = "replicas")))]
pub use crate::router::replicas::{ReplicaConfig, ReplicaFilter};
/// The default amount of jitter when waiting to reconnect.
pub const DEFAULT_JITTER_MS: u32 = 100;
/// Special errors that can trigger reconnection logic, which can also retry the failing command if possible.
///
/// `MOVED`, `ASK`, and `NOAUTH` errors are handled separately by the client.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg(feature = "custom-reconnect-errors")]
#[cfg_attr(docsrs, doc(cfg(feature = "custom-reconnect-errors")))]
pub enum ReconnectError {
/// The CLUSTERDOWN prefix.
ClusterDown,
/// The LOADING prefix.
Loading,
/// The MASTERDOWN prefix.
MasterDown,
/// The READONLY prefix, which can happen if a primary node is switched to a replica without any connection
/// interruption.
ReadOnly,
/// The MISCONF prefix.
Misconf,
/// The BUSY prefix.
Busy,
/// The NOREPLICAS prefix.
NoReplicas,
/// A case-sensitive prefix on an error message.
///
/// See [the source](https://github.com/redis/redis/blob/fe37e4fc874a92dcf61b3b0de899ec6f674d2442/src/server.c#L1845) for examples.
Custom(&'static str),
}
#[cfg(feature = "custom-reconnect-errors")]
impl ReconnectError {
pub(crate) fn to_str(&self) -> &'static str {
use ReconnectError::*;
match self {
ClusterDown => "CLUSTERDOWN",
Loading => "LOADING",
MasterDown => "MASTERDOWN",
ReadOnly => "READONLY",
Misconf => "MISCONF",
Busy => "BUSY",
NoReplicas => "NOREPLICAS",
Custom(prefix) => prefix,
}
}
}
/// The type of reconnection policy to use. This will apply to every connection used by the client.
///
/// Use a `max_attempts` value of `0` to retry forever.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReconnectPolicy {
/// Wait a constant amount of time between reconnect attempts, in ms.
Constant {
attempts: u32,
max_attempts: u32,
delay: u32,
jitter: u32,
},
/// Backoff reconnection attempts linearly, adding `delay` each time.
Linear {
attempts: u32,
max_attempts: u32,
max_delay: u32,
delay: u32,
jitter: u32,
},
/// Backoff reconnection attempts exponentially, multiplying the last delay by `base` each time.
Exponential {
attempts: u32,
max_attempts: u32,
min_delay: u32,
max_delay: u32,
base: u32,
jitter: u32,
},
}
impl Default for ReconnectPolicy {
fn default() -> Self {
ReconnectPolicy::Constant {
attempts: 0,
max_attempts: 0,
delay: 1000,
jitter: DEFAULT_JITTER_MS,
}
}
}
impl ReconnectPolicy {
/// Create a new reconnect policy with a constant backoff.
pub fn new_constant(max_attempts: u32, delay: u32) -> ReconnectPolicy {
ReconnectPolicy::Constant {
max_attempts,
delay,
attempts: 0,
jitter: DEFAULT_JITTER_MS,
}
}
/// Create a new reconnect policy with a linear backoff.
pub fn new_linear(max_attempts: u32, max_delay: u32, delay: u32) -> ReconnectPolicy {
ReconnectPolicy::Linear {
max_attempts,
max_delay,
delay,
attempts: 0,
jitter: DEFAULT_JITTER_MS,
}
}
/// Create a new reconnect policy with an exponential backoff.
pub fn new_exponential(max_attempts: u32, min_delay: u32, max_delay: u32, base: u32) -> ReconnectPolicy {
ReconnectPolicy::Exponential {
max_delay,
max_attempts,
min_delay,
base,
attempts: 0,
jitter: DEFAULT_JITTER_MS,
}
}
/// Set the amount of jitter to add to each reconnect delay.
///
/// Default: 50 ms
pub fn set_jitter(&mut self, jitter_ms: u32) {
match self {
ReconnectPolicy::Constant { ref mut jitter, .. } => {
*jitter = jitter_ms;
},
ReconnectPolicy::Linear { ref mut jitter, .. } => {
*jitter = jitter_ms;
},
ReconnectPolicy::Exponential { ref mut jitter, .. } => {
*jitter = jitter_ms;
},
}
}
/// Reset the number of reconnection attempts.
pub(crate) fn reset_attempts(&mut self) {
match *self {
ReconnectPolicy::Constant { ref mut attempts, .. } => {
*attempts = 0;
},
ReconnectPolicy::Linear { ref mut attempts, .. } => {
*attempts = 0;
},
ReconnectPolicy::Exponential { ref mut attempts, .. } => {
*attempts = 0;
},
}
}
/// Read the number of reconnection attempts.
pub fn attempts(&self) -> u32 {
match self {
ReconnectPolicy::Constant { ref attempts, .. } => *attempts,
ReconnectPolicy::Linear { ref attempts, .. } => *attempts,
ReconnectPolicy::Exponential { ref attempts, .. } => *attempts,
}
}
/// Read the max number of reconnection attempts.
pub fn max_attempts(&self) -> u32 {
match self {
ReconnectPolicy::Constant { ref max_attempts, .. } => *max_attempts,
ReconnectPolicy::Linear { ref max_attempts, .. } => *max_attempts,
ReconnectPolicy::Exponential { ref max_attempts, .. } => *max_attempts,
}
}
/// Whether the client should initiate a reconnect.
pub(crate) fn should_reconnect(&self) -> bool {
match *self {
ReconnectPolicy::Constant {
ref attempts,
ref max_attempts,
..
} => *max_attempts == 0 || *attempts < *max_attempts,
ReconnectPolicy::Linear {
ref attempts,
ref max_attempts,
..
} => *max_attempts == 0 || *attempts < *max_attempts,
ReconnectPolicy::Exponential {
ref attempts,
ref max_attempts,
..
} => *max_attempts == 0 || *attempts < *max_attempts,
}
}
/// Calculate the next delay, incrementing `attempts` in the process.
pub fn next_delay(&mut self) -> Option<u64> {
match *self {
ReconnectPolicy::Constant {
ref mut attempts,
delay,
max_attempts,
jitter,
} => {
*attempts = match utils::incr_with_max(*attempts, max_attempts) {
Some(a) => a,
None => return None,
};
Some(utils::add_jitter(delay as u64, jitter))
},
ReconnectPolicy::Linear {
ref mut attempts,
max_delay,
max_attempts,
delay,
jitter,
} => {
*attempts = match utils::incr_with_max(*attempts, max_attempts) {
Some(a) => a,
None => return None,
};
let delay = (delay as u64).saturating_mul(*attempts as u64);
Some(cmp::min(max_delay as u64, utils::add_jitter(delay, jitter)))
},
ReconnectPolicy::Exponential {
ref mut attempts,
min_delay,
max_delay,
max_attempts,
base,
jitter,
} => {
*attempts = match utils::incr_with_max(*attempts, max_attempts) {
Some(a) => a,
None => return None,
};
let delay = (base as u64)
.saturating_pow(*attempts - 1)
.saturating_mul(min_delay as u64);
Some(cmp::min(max_delay as u64, utils::add_jitter(delay, jitter)))
},
}
}
}
/// Describes how the client should respond when a command is sent while the client is in a blocked state from a
/// blocking command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Blocking {
/// Wait to send the command until the blocked command finishes. (Default)
Block,
/// Return an error to the caller.
Error,
/// Interrupt the blocked command by automatically sending `CLIENT UNBLOCK` for the blocked connection.
Interrupt,
}
impl Default for Blocking {
fn default() -> Self {
Blocking::Block
}
}
/// TCP configuration options.
#[derive(Clone, Debug, Default)]
pub struct TcpConfig {
/// Set the [TCP_NODELAY](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html#method.set_nodelay) value.
pub nodelay: Option<bool>,
/// Set the [SO_LINGER](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html#method.set_linger) value.
pub linger: Option<Duration>,
/// Set the [IP_TTL](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html#method.set_ttl) value.
pub ttl: Option<u32>,
/// Set the [TCP keepalive values](https://docs.rs/socket2/latest/socket2/struct.Socket.html#method.set_tcp_keepalive).
pub keepalive: Option<TcpKeepalive>,
}
impl PartialEq for TcpConfig {
fn eq(&self, other: &Self) -> bool {
self.nodelay == other.nodelay && self.linger == other.linger && self.ttl == other.ttl
}
}
impl Eq for TcpConfig {}
/// Configuration options used to detect potentially unresponsive connections.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnresponsiveConfig {
/// If provided, the amount of time a frame can wait without a response before the associated connection is
/// considered unresponsive.
///
/// If a connection is considered unresponsive it will be forcefully closed and the client will reconnect based on
/// the [ReconnectPolicy](crate::types::config::ReconnectPolicy). This heuristic can be useful in environments
/// where connections may close or change in subtle or unexpected ways.
///
/// Unlike the [timeout](crate::types::config::Options) and
/// [default_command_timeout](crate::types::config::PerformanceConfig) interfaces, any in-flight commands waiting
/// on a response when the connection is closed this way will be retried based on the associated
/// [ReconnectPolicy](crate::types::config::ReconnectPolicy) and [Options](crate::types::config::Options).
///
/// Default: `None`
pub max_timeout: Option<Duration>,
/// The frequency at which the client checks for unresponsive connections.
///
/// This value should usually be less than half of `max_timeout` and always more than 1 ms.
///
/// Default: 2 sec
pub interval: Duration,
}
impl Default for UnresponsiveConfig {
fn default() -> Self {
UnresponsiveConfig {
max_timeout: None,
interval: Duration::from_secs(2),
}
}
}
/// A policy that determines how clustered clients initially connect to and discover other cluster nodes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClusterDiscoveryPolicy {
/// Always use the endpoint(s) provided in the client's [ServerConfig](ServerConfig).
///
/// This is generally recommended with managed services, Kubernetes, or other systems that provide client routing
/// or cluster discovery interfaces.
///
/// Default.
ConfigEndpoint,
/// Try connecting to nodes specified in both the client's [ServerConfig](ServerConfig) and the most recently
/// cached routing table.
UseCache,
}
impl Default for ClusterDiscoveryPolicy {
fn default() -> Self {
ClusterDiscoveryPolicy::ConfigEndpoint
}
}
/// Configuration options related to the creation or management of TCP connection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConnectionConfig {
/// The timeout to apply when attempting to create a new TCP connection.
///
/// This also includes the TLS handshake if using any of the TLS features.
///
/// Default: 10 sec
pub connection_timeout: Duration,
/// The timeout to apply when sending internal commands such as `AUTH`, `SELECT`, `CLUSTER SLOTS`, `READONLY`, etc.
///
/// Default: 10 sec
pub internal_command_timeout: Duration,
/// The amount of time to wait after a `MOVED` error is received before the client will update the cached cluster
/// state.
///
/// Default: `0`
pub cluster_cache_update_delay: Duration,
/// The maximum number of times the client will attempt to send a command.
///
/// This value be incremented whenever the connection closes while the command is in-flight.
///
/// Default: `3`
pub max_command_attempts: u32,
/// The maximum number of times the client will attempt to follow a `MOVED` or `ASK` redirection per command.
///
/// Default: `5`
pub max_redirections: u32,
/// Unresponsive connection configuration options.
pub unresponsive: UnresponsiveConfig,
/// An unexpected `NOAUTH` error is treated the same as a general connection failure, causing the client to
/// reconnect based on the [ReconnectPolicy](crate::types::config::ReconnectPolicy). This is [recommended](https://github.com/StackExchange/StackExchange.Redis/issues/1273#issuecomment-651823824) if callers are using ElastiCache.
///
/// Default: `false`
pub reconnect_on_auth_error: bool,
/// Automatically send `CLIENT SETNAME` on each connection associated with a client instance.
///
/// Default: `false`
pub auto_client_setname: bool,
/// Limit the size of the internal in-memory command queue.
///
/// Commands that exceed this limit will receive a `ErrorKind::Backpressure` error. Setting this value to
/// anything > 0 will indicate that the client should use a bounded MPSC channel to communicate with the routing
/// task.
///
/// See [command_queue_len](crate::interfaces::MetricsInterface::command_queue_len) for more information.
///
/// Default: `0` (unlimited)
pub max_command_buffer_len: usize,
/// Disable the `CLUSTER INFO` health check when initializing cluster connections.
///
/// Default: `false`
pub disable_cluster_health_check: bool,
/// Configuration options for replica nodes.
///
/// Default: `None`
#[cfg(feature = "replicas")]
#[cfg_attr(docsrs, doc(cfg(feature = "replicas")))]
pub replica: ReplicaConfig,
/// TCP connection options.
pub tcp: TcpConfig,
/// Errors that should trigger reconnection logic.
#[cfg(feature = "custom-reconnect-errors")]
#[cfg_attr(docsrs, doc(cfg(feature = "custom-reconnect-errors")))]
pub reconnect_errors: Vec<ReconnectError>,
/// The task queue onto which routing tasks will be spawned.
///
/// May cause a panic if [spawn_local_into](glommio::spawn_local_into) fails.
#[cfg(feature = "glommio")]
#[cfg_attr(docsrs, doc(cfg(feature = "glommio")))]
pub router_task_queue: Option<glommio::TaskQueueHandle>,
/// The task queue onto which connection reader tasks will be spawned.
///
/// May cause a panic if [spawn_local_into](glommio::spawn_local_into) fails.
#[cfg(feature = "glommio")]
#[cfg_attr(docsrs, doc(cfg(feature = "glommio")))]
pub connection_task_queue: Option<glommio::TaskQueueHandle>,
}
impl Default for ConnectionConfig {
fn default() -> Self {
#[allow(deprecated)]
ConnectionConfig {
connection_timeout: Duration::from_millis(10_000),
internal_command_timeout: Duration::from_millis(10_000),
max_redirections: 5,
max_command_attempts: 3,
max_command_buffer_len: 0,
auto_client_setname: false,
cluster_cache_update_delay: Duration::from_millis(0),
reconnect_on_auth_error: false,
disable_cluster_health_check: false,
tcp: TcpConfig::default(),
unresponsive: UnresponsiveConfig::default(),
#[cfg(feature = "replicas")]
replica: ReplicaConfig::default(),
#[cfg(feature = "custom-reconnect-errors")]
reconnect_errors: vec![
ReconnectError::ClusterDown,
ReconnectError::Loading,
ReconnectError::ReadOnly,
],
#[cfg(feature = "glommio")]
router_task_queue: None,
#[cfg(feature = "glommio")]
connection_task_queue: None,
}
}
}
/// Configuration options that can affect the performance of the client.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PerformanceConfig {
/// An optional timeout to apply to all commands.
///
/// If `0` this will disable any timeout being applied to commands. Callers can also set timeouts on individual
/// commands via the [with_options](crate::interfaces::ClientLike::with_options) interface.
///
/// Default: `0`
pub default_command_timeout: Duration,
/// The maximum number of frames that will be fed to a socket before flushing.
///
/// Note: in some circumstances the client with always flush the socket (`QUIT`, `EXEC`, etc).
///
/// Default: 200
pub max_feed_count: u64,
/// The default capacity used when creating [broadcast channels](https://docs.rs/tokio/latest/tokio/sync/broadcast/fn.channel.html) in the [EventInterface](crate::interfaces::EventInterface).
///
/// Default: 32
pub broadcast_channel_capacity: usize,
/// The minimum size, in bytes, of frames that should be encoded or decoded with a blocking task.
///
/// See [block_in_place](https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html) for more information.
///
/// Default: 50_000_000
#[cfg(feature = "blocking-encoding")]
#[cfg_attr(docsrs, doc(cfg(feature = "blocking-encoding")))]
pub blocking_encode_threshold: usize,
}
impl Default for PerformanceConfig {
fn default() -> Self {
PerformanceConfig {
default_command_timeout: Duration::from_millis(0),
max_feed_count: 200,
broadcast_channel_capacity: 32,
#[cfg(feature = "blocking-encoding")]
blocking_encode_threshold: 50_000_000,
}
}
}
/// A trait that can be used to override the credentials used in each `AUTH` or `HELLO` command.
#[async_trait]
#[cfg(all(feature = "credential-provider", not(feature = "glommio")))]
#[cfg_attr(docsrs, doc(cfg(feature = "credential-provider")))]
pub trait CredentialProvider: Debug + Send + Sync + 'static {
/// Read the username and password that should be used in the next `AUTH` or `HELLO` command.
async fn fetch(&self, server: Option<&Server>) -> Result<(Option<String>, Option<String>), Error>;
/// Configure the client to call [fetch](Self::fetch) and send `AUTH` or `HELLO` on some interval.
fn refresh_interval(&self) -> Option<Duration> {
None
}
}
/// A trait that can be used to override the credentials used in each `AUTH` or `HELLO` command.
#[async_trait(?Send)]
#[cfg(all(feature = "credential-provider", feature = "glommio"))]
#[cfg_attr(docsrs, doc(cfg(feature = "credential-provider")))]
pub trait CredentialProvider: Debug + 'static {
/// Read the username and password that should be used in the next `AUTH` or `HELLO` command.
async fn fetch(&self, server: Option<&Server>) -> Result<(Option<String>, Option<String>), Error>;
/// Configure the client to call [fetch](Self::fetch) and send `AUTH` or `HELLO` on some interval.
fn refresh_interval(&self) -> Option<Duration> {
None
}
}
/// Configuration options for a `Client`.
#[derive(Clone, Debug)]
pub struct Config {
/// Whether the client should return an error if it cannot connect to the server the first time when being
/// initialized. If `false` the client will run the reconnect logic if it cannot connect to the server the first
/// time, but if `true` the client will return initial connection errors to the caller immediately.
///
/// Normally the reconnection logic only applies to connections that close unexpectedly, but this flag can apply
/// the same logic to the first connection as it is being created.
///
/// Callers should use caution setting this to `false` since it can make debugging configuration issues more
/// difficult.
///
/// Default: `true`
pub fail_fast: bool,
/// The default behavior of the client when a command is sent while the connection is blocked on a blocking
/// command.
///
/// Setting this to anything other than `Blocking::Block` incurs a small performance penalty.
///
/// Default: `Blocking::Block`
pub blocking: Blocking,
/// An optional ACL username for the client to use when authenticating. If ACL rules are not configured this should
/// be `None`.
///
/// Default: `None`
pub username: Option<String>,
/// An optional password for the client to use when authenticating.
///
/// Default: `None`
pub password: Option<String>,
/// Connection configuration for the server(s).
///
/// Default: `Centralized(localhost, 6379)`
pub server: ServerConfig,
/// The protocol version to use when communicating with the server(s).
///
/// If RESP3 is specified the client will automatically use `HELLO` when authenticating. **This requires version
/// 6.0.0 or above.** If the `HELLO` command fails this will prevent the client from connecting. Callers should set
/// this to RESP2 and use `HELLO` manually to fall back to RESP2 if needed.
///
/// Note: upgrading an existing codebase from RESP2 to RESP3 may require changing certain type signatures. RESP3
/// has a slightly different type system than RESP2.
///
/// Default: `RESP2`
pub version: RespVersion,
/// An optional database number that the client will automatically `SELECT` after connecting or reconnecting.
///
/// It is recommended that callers use this field instead of putting a `select()` call inside the `on_reconnect`
/// block, if possible. Commands that were in-flight when the connection closed will retry before anything inside
/// the `on_reconnect` block.
///
/// Default: `None`
pub database: Option<u8>,
/// TLS configuration options.
///
/// Default: `None`
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
#[cfg_attr(
docsrs,
doc(cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
)))
)]
pub tls: Option<TlsConfig>,
/// Tracing configuration options.
#[cfg(feature = "partial-tracing")]
#[cfg_attr(docsrs, doc(cfg(feature = "partial-tracing")))]
pub tracing: TracingConfig,
/// An optional [mocking layer](crate::mocks) to intercept and process commands.
///
/// Default: `None`
#[cfg(feature = "mocks")]
#[cfg_attr(docsrs, doc(cfg(feature = "mocks")))]
pub mocks: Option<Arc<dyn Mocks>>,
/// An optional credential provider callback interface.
///
/// Default: `None`
///
/// When used with the `sentinel-auth` feature this interface will take precedence over all `username` and
/// `password` fields for both sentinel nodes and servers.
#[cfg(feature = "credential-provider")]
#[cfg_attr(docsrs, doc(cfg(feature = "credential-provider")))]
pub credential_provider: Option<Arc<dyn CredentialProvider>>,
}
impl PartialEq for Config {
fn eq(&self, other: &Self) -> bool {
self.server == other.server
&& self.database == other.database
&& self.fail_fast == other.fail_fast
&& self.version == other.version
&& self.username == other.username
&& self.password == other.password
&& self.blocking == other.blocking
}
}
impl Eq for Config {}
impl Default for Config {
fn default() -> Self {
Config {
fail_fast: true,
blocking: Blocking::default(),
username: None,
password: None,
server: ServerConfig::default(),
version: RespVersion::RESP2,
database: None,
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
tls: None,
#[cfg(feature = "partial-tracing")]
tracing: TracingConfig::default(),
#[cfg(feature = "mocks")]
mocks: None,
#[cfg(feature = "credential-provider")]
credential_provider: None,
}
}
}
#[cfg_attr(docsrs, allow(rustdoc::broken_intra_doc_links))]
impl Config {
/// Whether the client uses TLS.
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
pub fn uses_tls(&self) -> bool {
self.tls.is_some()
}
/// Whether the client uses TLS.
#[cfg(not(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
)))]
pub fn uses_tls(&self) -> bool {
false
}
/// Whether the client uses a `native-tls` connector.
#[cfg(feature = "enable-native-tls")]
pub fn uses_native_tls(&self) -> bool {
self
.tls
.as_ref()
.map(|config| matches!(config.connector, TlsConnector::Native(_)))
.unwrap_or(false)
}
/// Whether the client uses a `native-tls` connector.
#[cfg(not(feature = "enable-native-tls"))]
pub fn uses_native_tls(&self) -> bool {
false
}
/// Whether the client uses a `rustls` connector.
#[cfg(any(feature = "enable-rustls", feature = "enable-rustls-ring"))]
pub fn uses_rustls(&self) -> bool {
self
.tls
.as_ref()
.map(|config| matches!(config.connector, TlsConnector::Rustls(_)))
.unwrap_or(false)
}
/// Whether the client uses a `rustls` connector.
#[cfg(not(any(feature = "enable-rustls", feature = "enable-rustls-ring")))]
pub fn uses_rustls(&self) -> bool {
false
}
/// Parse a URL string into a `Config`.
///
/// # URL Syntax
///
/// **Centralized**
///
/// ```text
/// redis|rediss :// [[username:]password@] host [:port][/database]
/// ```
///
/// **Clustered**
///
/// ```text
/// redis|rediss[-cluster] :// [[username:]password@] host [:port][?[node=host1:port1][&node=host2:port2][&node=hostN:portN]]
/// ```
///
/// **Sentinel**
///
/// ```text
/// redis|rediss[-sentinel] :// [[username1:]password1@] host [:port][/database][?[node=host1:port1][&node=host2:port2][&node=hostN:portN]
/// [&sentinelServiceName=myservice][&sentinelUsername=username2][&sentinelPassword=password2]]
/// ```
///
/// **Unix Socket**
///
/// ```text
/// redis+unix:// [[username:]password@] /path/to/redis.sock
/// ```
///
/// # Schemes
///
/// This function will use the URL scheme to determine which server type the caller is using. Valid schemes include:
///
/// * `redis|valkey` - TCP connected to a centralized server.
/// * `rediss|valkeys` - TLS connected to a centralized server.
/// * `redis-cluster|valkey-cluster` - TCP connected to a cluster.
/// * `rediss-cluster|valkeys-cluster` - TLS connected to a cluster.
/// * `redis-sentinel|valkey-sentinel` - TCP connected to a centralized server behind a sentinel layer.
/// * `rediss-sentinel|valkeys-sentinel` - TLS connected to a centralized server behind a sentinel layer.
/// * `redis+unix|valkey+unix` - Unix domain socket followed by a path.
///
/// **The `rediss|valkeys` scheme prefix requires one of the TLS feature flags.**
///
/// # Query Parameters
///
/// In some cases it's necessary to specify multiple node hostname/port tuples (with a cluster or sentinel layer for
/// example). The following query parameters may also be used in their respective contexts:
///
/// * `node` - Specify another node in the topology. In a cluster this would refer to any other known cluster node.
/// In the context of a sentinel layer this refers to a known **sentinel** node. Multiple `node` parameters may be
/// used in a URL.
/// * `sentinelServiceName` - Specify the name of the sentinel service. This is required when using the
/// `redis-sentinel` scheme.
/// * `sentinelUsername` - Specify the username to use when connecting to a **sentinel** node. This requires the
/// `sentinel-auth` feature and allows the caller to use different credentials for sentinel nodes vs the actual
/// server. The `username` part of the URL immediately following the scheme will refer to the username used when
/// connecting to the backing server.
/// * `sentinelPassword` - Specify the password to use when connecting to a **sentinel** node. This requires the
/// `sentinel-auth` feature and allows the caller to use different credentials for sentinel nodes vs the actual
/// server. The `password` part of the URL immediately following the scheme will refer to the password used when
/// connecting to the backing server.
///
/// See the [from_url_centralized](Self::from_url_centralized), [from_url_clustered](Self::from_url_clustered),
/// [from_url_sentinel](Self::from_url_sentinel), and [from_url_unix](Self::from_url_unix) for more information. Or
/// see the [Config](Self) unit tests for examples.
pub fn from_url(url: &str) -> Result<Config, Error> {
let parsed_url = Url::parse(url)?;
if utils::url_is_clustered(&parsed_url) {
Config::from_url_clustered(url)
} else if utils::url_is_sentinel(&parsed_url) {
Config::from_url_sentinel(url)
} else if utils::url_is_unix_socket(&parsed_url) {
#[cfg(feature = "unix-sockets")]
return Config::from_url_unix(url);
#[allow(unreachable_code)]
Err(Error::new(ErrorKind::Config, "Missing unix-socket feature."))
} else {
Config::from_url_centralized(url)
}
}
/// Create a centralized `Config` struct from a URL.
///
/// ```text
/// redis://username:[email protected]:6379/1
/// rediss://username:[email protected]:6379/1
/// redis://foo.com:6379/1
/// redis://foo.com
/// // ... etc
/// ```
///
/// This function is very similar to [from_url](Self::from_url), but it adds a layer of validation for configuration
/// parameters that are only relevant to a centralized server.
///
/// For example:
///
/// * A database can be defined in the `path` section.
/// * The `port` field is optional in this context. If it is not specified then `6379` will be used.
/// * Any `node` or sentinel query parameters will be ignored.
pub fn from_url_centralized(url: &str) -> Result<Config, Error> {
let (url, host, port, _tls) = utils::parse_url(url, Some(6379))?;
let server = ServerConfig::new_centralized(host, port);
let database = utils::parse_url_db(&url)?;
let (username, password) = utils::parse_url_credentials(&url)?;
Ok(Config {
server,
username,
password,
database,
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
tls: utils::tls_config_from_url(_tls)?,
..Config::default()
})
}
/// Create a clustered `Config` struct from a URL.
///
/// ```text
/// redis-cluster://username:[email protected]:30001?node=bar.com:30002&node=baz.com:30003
/// rediss-cluster://username:[email protected]:30001?node=bar.com:30002&node=baz.com:30003
/// rediss://foo.com:30001?node=bar.com:30002&node=baz.com:30003
/// redis://foo.com:30001
/// // ... etc
/// ```
///
/// This function is very similar to [from_url](Self::from_url), but it adds a layer of validation for configuration
/// parameters that are only relevant to a clustered deployment.
///
/// For example:
///
/// * The `-cluster` suffix in the scheme is optional when using this function directly.
/// * Any database defined in the `path` section will be ignored.
/// * The `port` field is required in this context alongside any hostname.
/// * Any `node` query parameters will be used to find other known cluster nodes.
/// * Any sentinel query parameters will be ignored.
pub fn from_url_clustered(url: &str) -> Result<Config, Error> {
let (url, host, port, _tls) = utils::parse_url(url, Some(6379))?;
let mut cluster_nodes = utils::parse_url_other_nodes(&url)?;
cluster_nodes.push(Server::new(host, port));
let server = ServerConfig::Clustered {
hosts: cluster_nodes,
policy: ClusterDiscoveryPolicy::default(),
};
let (username, password) = utils::parse_url_credentials(&url)?;
Ok(Config {
server,
username,
password,
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
tls: utils::tls_config_from_url(_tls)?,
..Config::default()
})
}
/// Create a sentinel `Config` struct from a URL.
///
/// ```text
/// redis-sentinel://username:[email protected]:6379/1?sentinelServiceName=fakename&node=foo.com:30001&node=bar.com:30002
/// rediss-sentinel://username:[email protected]:6379/0?sentinelServiceName=fakename&node=foo.com:30001&node=bar.com:30002
/// redis://foo.com:6379?sentinelServiceName=fakename
/// rediss://foo.com:6379/1?sentinelServiceName=fakename
/// // ... etc
/// ```
///
/// This function is very similar to [from_url](Self::from_url), but it adds a layer of validation for configuration
/// parameters that are only relevant to a sentinel deployment.
///
/// For example:
///
/// * The `-sentinel` suffix in the scheme is optional when using this function directly.
/// * A database can be defined in the `path` section.
/// * The `port` field is optional following the first hostname (`26379` will be used if undefined), but required
/// within any `node` query parameters.
/// * Any `node` query parameters will be used to find other known sentinel nodes.
/// * The `sentinelServiceName` query parameter is required.
/// * Depending on the cargo features used other sentinel query parameters may be used.
///
/// This particular function is more complex than the others when the `sentinel-auth` feature is used. For example,
/// to declare a config that uses different credentials for the sentinel nodes vs the backing servers:
///
/// ```text
/// redis-sentinel://username1:[email protected]:26379/1?sentinelServiceName=fakename&sentinelUsername=username2&sentinelPassword=password2&node=bar.com:26379&node=baz.com:26380
/// ```
///
/// The above example will use `("username1", "password1")` when authenticating to the backing servers, and
/// `("username2", "password2")` when initially connecting to the sentinel nodes. Additionally, all 3 addresses
/// (`foo.com:26379`, `bar.com:26379`, `baz.com:26380`) specify known **sentinel** nodes.
pub fn from_url_sentinel(url: &str) -> Result<Config, Error> {
let (url, host, port, _tls) = utils::parse_url(url, Some(26379))?;
let mut other_nodes = utils::parse_url_other_nodes(&url)?;
other_nodes.push(Server::new(host, port));
let service_name = utils::parse_url_sentinel_service_name(&url)?;
let (username, password) = utils::parse_url_credentials(&url)?;
let database = utils::parse_url_db(&url)?;
let server = ServerConfig::Sentinel {
hosts: other_nodes,
service_name,
#[cfg(feature = "sentinel-auth")]
username: utils::parse_url_sentinel_username(&url),
#[cfg(feature = "sentinel-auth")]
password: utils::parse_url_sentinel_password(&url),
};
Ok(Config {
server,
username,
password,
database,
#[cfg(any(
feature = "enable-native-tls",
feature = "enable-rustls",
feature = "enable-rustls-ring"
))]
tls: utils::tls_config_from_url(_tls)?,
..Config::default()
})
}
/// Create a `Config` from a URL that connects via a Unix domain socket.
///
/// ```text
/// redis+unix:///path/to/redis.sock
/// redis+unix://username:password@nonemptyhost/path/to/redis.sock
/// ```
///
/// **Important**
///
/// * In the other URL parsing functions the path section indicates the database that the client should `SELECT`
/// after connecting. However, Unix sockets are also specified by a path rather than a hostname:port, which
/// creates some ambiguity in this case. Callers should manually set the database field on the returned `Config`
/// if needed.
/// * If credentials are provided the caller must also specify a hostname in order to pass to the [URL
/// validation](Url::parse) process. This function will ignore the value, but some non-empty string must be
/// provided.
#[cfg(feature = "unix-sockets")]
#[cfg_attr(docsrs, doc(cfg(feature = "unix-sockets")))]
pub fn from_url_unix(url: &str) -> Result<Config, Error> {
let (url, path) = utils::parse_unix_url(url)?;
let (username, password) = utils::parse_url_credentials(&url)?;