rustis 0.25.0

Redis async driver for Rust
Documentation
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
use crate::{
    ClientError, ErrorKind, Result,
    client::{Config, Credentials, IntoConfig, ReconnectionConfig, SentinelConfig, ServerConfig},
};
use std::sync::Arc;

#[tokio::test]
async fn credentials_provider_wins_over_static() -> Result<()> {
    let mut config = Config {
        username: Some("static_user".to_owned()),
        password: Some("static_pwd".to_owned()),
        credentials_provider: Some(Arc::new(|| async {
            Ok(Credentials {
                username: Some("dynamic_user".to_owned()),
                password: "dynamic_pwd".to_owned(),
            })
        })),
        ..Default::default()
    };

    let credentials = config.resolve_credentials().await?.unwrap();
    assert_eq!(Some("dynamic_user"), credentials.username.as_deref());
    assert_eq!("dynamic_pwd", credentials.password);

    // Without a provider, the static fields still drive the handshake.
    config.credentials_provider = None;
    let credentials = config.resolve_credentials().await?.unwrap();
    assert_eq!(Some("static_user"), credentials.username.as_deref());
    assert_eq!("static_pwd", credentials.password);

    Ok(())
}

#[test]
fn provider_debug_does_not_leak() -> Result<()> {
    let config = Config {
        credentials_provider: Some(Arc::new(|| async {
            Ok(Credentials {
                username: None,
                password: "dynamic_pwd".to_owned(),
            })
        })),
        ..Default::default()
    };

    let debug = format!("{config:?}");
    assert!(
        !debug.contains("dynamic_pwd"),
        "Debug leaked the password: {debug}"
    );
    let display = config.to_string();
    assert!(
        !display.contains("dynamic_pwd"),
        "Display leaked the password: {display}"
    );

    Ok(())
}

#[test]
fn display_masks_password() -> Result<()> {
    // Display is the natural way to log a config; it must never leak the
    // password in clear text.
    assert_eq!(
        "redis://:***@127.0.0.1",
        "redis://:pwd@127.0.0.1".into_config()?.to_string()
    );
    assert_eq!(
        "redis://username:***@127.0.0.1",
        "redis://username:pwd@127.0.0.1".into_config()?.to_string()
    );
    assert_eq!(
        "redis+sentinel://127.0.0.1:6379/myservice?sentinel_username=foo&sentinel_password=***",
        "redis+sentinel://127.0.0.1:6379/myservice?sentinel_username=foo&sentinel_password=bar"
            .into_config()?
            .to_string()
    );

    // Debug must not leak the password either.
    let debug = format!("{:?}", "redis://username:pwd@127.0.0.1".into_config()?);
    assert!(!debug.contains("pwd"), "Debug leaked the password: {debug}");
    Ok(())
}

#[test]
fn into_config() -> Result<()> {
    assert_eq!("redis://127.0.0.1", "127.0.0.1".into_config()?.to_string());
    assert_eq!(
        "redis://127.0.0.1",
        "127.0.0.1:6379".into_config()?.to_string()
    );
    assert_eq!(
        "redis://127.0.0.1",
        "127.0.0.1".to_owned().into_config()?.to_string()
    );
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1:6379".into_config()?.to_string()
    );
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1".into_config()?.to_string()
    );
    assert_eq!(
        "redis://example.com",
        "redis://example.com".into_config()?.to_string()
    );
    assert_eq!(
        "redis://:***@127.0.0.1",
        "redis://:pwd@127.0.0.1".into_config()?.to_string()
    );
    assert_eq!(
        "redis://username:***@127.0.0.1",
        "redis://username:pwd@127.0.0.1".into_config()?.to_string()
    );
    assert_eq!(
        "redis://username:***@127.0.0.1/1",
        "redis://username:pwd@127.0.0.1/1"
            .into_config()?
            .to_string()
    );
    #[cfg(any(feature = "native-tls", feature = "rustls"))]
    assert_eq!(
        "rediss://username:***@127.0.0.1/1",
        "rediss://username:pwd@127.0.0.1/1"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?connect_timeout=100",
        "redis://127.0.0.1?connect_timeout=100"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1?auto_resubscribe=true"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?auto_resubscribe=false",
        "redis://127.0.0.1?auto_resubscribe=false"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1?auto_remonitor=true"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?auto_remonitor=false",
        "redis://127.0.0.1?auto_remonitor=false"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?connection_name=myclient",
        "redis://127.0.0.1?connection_name=myclient"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?keep_alive=60000",
        "redis://127.0.0.1?keep_alive=60000"
            .into_config()?
            .to_string()
    );
    // the default keep-alive is implicit in the URL
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1?keep_alive=30000"
            .into_config()?
            .to_string()
    );
    // 0 means "no keep-alive" and must survive a round-trip
    assert_eq!(
        "redis://127.0.0.1?keep_alive=0",
        "redis://127.0.0.1?keep_alive=0".into_config()?.to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?no_delay=false",
        "redis://127.0.0.1?no_delay=false"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?retry_on_error=true",
        "redis://127.0.0.1?retry_on_error=true"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?max_command_attempts=2",
        "redis://127.0.0.1?max_command_attempts=2"
            .into_config()?
            .to_string()
    );
    // a knob left at its default is implicit in the URL, whichever struct holds it
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1?buffers.shrink_factor=8&limits.max_nesting_depth=128"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?buffers.read_capacity=1024&backpressure.max_push_bytes=0&limits.max_bulk_length=1048576",
        "redis://127.0.0.1?buffers.read_capacity=1024&backpressure.max_push_bytes=0&limits.max_bulk_length=1048576"
            .into_config()?
            .to_string()
    );
    // the default policy is implicit, any other one is written out in full so it
    // survives the round trip whatever the reader's defaults are
    assert_eq!(
        "redis://127.0.0.1",
        "redis://127.0.0.1?reconnection=constant"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?reconnection=constant&reconnection.max_attempts=3&reconnection.delay=1000&reconnection.jitter=100",
        "redis://127.0.0.1?reconnection=constant&reconnection.max_attempts=3"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?reconnection=linear&reconnection.max_attempts=0&reconnection.delay=100&reconnection.max_delay=5000&reconnection.jitter=100",
        "redis://127.0.0.1?reconnection=linear&reconnection.delay=100&reconnection.max_delay=5000"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis://127.0.0.1?reconnection=exponential&reconnection.max_attempts=0&reconnection.min_delay=50&reconnection.max_delay=10000&reconnection.multiplicative_factor=2&reconnection.jitter=100",
        "redis://127.0.0.1?reconnection=exponential&reconnection.min_delay=50&reconnection.max_delay=10000&reconnection.multiplicative_factor=2"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice/1",
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice/1"
            .into_config()?
            .to_string()
    );
    assert_eq!(
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice/1",
        "redis-sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice/1"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice",
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://username:***@127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice",
        "redis+sentinel://username:pwd@127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://:***@127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice",
        "redis+sentinel://:pwd@127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381/myservice"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379/myservice",
        "redis+sentinel://127.0.0.1:6379/myservice"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379/myservice?wait_between_failures=100&sentinel_username=foo&sentinel_password=***",
        "redis+sentinel://127.0.0.1:6379/myservice?wait_between_failures=100&sentinel_username=foo&sentinel_password=***"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379/myservice?sentinel_username=foo&sentinel_password=***",
        "redis+sentinel://127.0.0.1:6379/myservice?wait_between_failures=250&sentinel_username=foo&sentinel_password=***"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+sentinel://127.0.0.1:6379/myservice?connect_timeout=100&wait_between_failures=100&sentinel_username=foo&sentinel_password=***",
        "redis+sentinel://127.0.0.1:6379/myservice?connect_timeout=100&wait_between_failures=100&sentinel_username=foo&sentinel_password=***"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+cluster://127.0.0.1:7000,127.0.0.1:7001",
        "redis+cluster://127.0.0.1:7000,127.0.0.1:7001"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+cluster://127.0.0.1:7000?read_preference=prefer_replica",
        "redis+cluster://127.0.0.1:7000?read_preference=prefer_replica"
            .into_config()?
            .to_string()
    );

    // the default read preference is implicit in the URL
    assert_eq!(
        "redis+cluster://127.0.0.1:7000",
        "redis+cluster://127.0.0.1:7000?read_preference=master"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+cluster://127.0.0.1:7000?connect_timeout=100&read_preference=prefer_replica",
        "redis+cluster://127.0.0.1:7000?connect_timeout=100&read_preference=prefer_replica"
            .into_config()?
            .to_string()
    );

    assert_eq!(
        "redis+cluster://127.0.0.1:7000?topology_refresh_interval=5000",
        "redis+cluster://127.0.0.1:7000?topology_refresh_interval=5000"
            .into_config()?
            .to_string()
    );

    // `0` means no proactive refresh, and is not the default, so it survives the
    // round trip rather than being folded away.
    assert_eq!(
        "redis+cluster://127.0.0.1:7000?topology_refresh_interval=0",
        "redis+cluster://127.0.0.1:7000?topology_refresh_interval=0"
            .into_config()?
            .to_string()
    );

    // the default interval is implicit in the URL
    assert_eq!(
        "redis+cluster://127.0.0.1:7000",
        "redis+cluster://127.0.0.1:7000?topology_refresh_interval=60000"
            .into_config()?
            .to_string()
    );

    assert!("127.0.0.1:xyz".into_config().is_err());
    assert!("redis://127.0.0.1:xyz".into_config().is_err());
    assert!("redis://username@127.0.0.1".into_config().is_err());
    assert!("http://username@127.0.0.1".into_config().is_err());
    assert!(
        "redis+sentinel://127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381"
            .into_config()
            .is_err()
    );
    assert!("redis://127.0.0.1?param".into_config().is_err());

    Ok(())
}

#[test]
fn an_unknown_query_parameter_is_rejected() {
    // A misspelled knob used to be dropped without a word, leaving the default
    // in place while the caller believed they had set it.
    for uri in [
        "redis://127.0.0.1?param=value",
        "redis://127.0.0.1?commandtimeout=5000",
        "redis://127.0.0.1?command_timeout=5000&read_timeout=5000",
        // a knob is addressed by the field it sets, not by the struct alone
        "redis://127.0.0.1?buffers=1024",
        "redis://127.0.0.1?limits.max_bulk_len=1024",
        "redis+sentinel://127.0.0.1:6379/myservice?sentinel_user=foo",
    ] {
        let error = uri.into_config().unwrap_err();
        let ErrorKind::Client(ClientError::InvalidUri(message)) = error.kind() else {
            panic!("`{uri}` should be rejected as an unknown query parameter");
        };
        assert!(
            message.contains("unknown"),
            "`{uri}`: unhelpful message `{message}`"
        );
    }
}

/// A parameter only one server type reads is rejected on every other, naming
/// the URI it belongs to.
///
/// These are real parameters, so reporting them as unknown sends the caller
/// looking for a typo that is not there: what is wrong is the scheme they were
/// written on.
#[test]
fn a_query_parameter_of_another_server_type_names_the_uri_it_belongs_to() {
    for (uri, belongs_to) in [
        ("redis://127.0.0.1?sentinel_password=secret", "sentinel"),
        (
            "redis+cluster://127.0.0.1:6379?sentinel_username=foo",
            "sentinel",
        ),
        (
            "redis+cluster://127.0.0.1:6379?wait_between_failures=250",
            "sentinel",
        ),
        (
            "redis://127.0.0.1?read_preference=prefer_replica",
            "cluster",
        ),
        (
            "redis+sentinel://127.0.0.1:6379/myservice?topology_refresh_interval=60000",
            "cluster",
        ),
        // the TCP schemes have a database, spelled as a path segment
        ("redis://127.0.0.1?db=5", "unix socket"),
    ] {
        let error = uri.into_config().unwrap_err();
        let ErrorKind::Client(ClientError::InvalidUri(message)) = error.kind() else {
            panic!("`{uri}` should be rejected as a parameter of another server type");
        };
        let name = uri.rsplit_once('?').unwrap().1.split('=').next().unwrap();
        assert!(
            message.contains(name) && message.contains(belongs_to),
            "`{uri}`: message `{message}` names neither `{name}` nor the {belongs_to} URI it \
             belongs to"
        );
    }
}

#[test]
fn an_unparsable_query_parameter_value_is_rejected() {
    for uri in [
        "redis://127.0.0.1?command_timeout=5s",
        "redis://127.0.0.1?connect_timeout=5000ms",
        "redis://127.0.0.1?keep_alive=abc",
        "redis://127.0.0.1?no_delay=yes",
        "redis://127.0.0.1?auto_resubscribe=1",
        "redis://127.0.0.1?auto_remonitor=",
        "redis://127.0.0.1?retry_on_error=maybe",
        "redis://127.0.0.1?max_command_attempts=-1",
        "redis+sentinel://127.0.0.1:6379/myservice?wait_between_failures=250ms",
        "redis+cluster://127.0.0.1:7000?read_preference=replica",
    ] {
        let error = uri.into_config().unwrap_err();
        let ErrorKind::Client(ClientError::InvalidUri(message)) = error.kind() else {
            panic!("`{uri}` should be rejected as an unparsable parameter value");
        };
        let name = uri.rsplit_once('?').unwrap().1.split('=').next().unwrap();
        assert!(
            message.contains(name),
            "`{uri}`: message `{message}` does not name the offending parameter"
        );
    }
}

#[test]
fn the_default_config_detects_a_half_open_connection() {
    // With neither a command timeout nor a TCP keep-alive, a socket silently
    // dropped by a NAT or a load balancer is reported by nothing and every
    // awaiting caller parks forever. The keep-alive is what breaks that tie.
    let config = Config::default();

    assert_eq!(Some(std::time::Duration::from_secs(30)), config.keep_alive);
}

#[test]
fn tuning_defaults_preserve_the_historical_hardcoded_values() {
    // These knobs were compile-time constants before they became configurable.
    // Their defaults are the values that shipped, so exposing them changes
    // nothing for a caller who does not touch them.
    let config = Config::default();

    assert_eq!(64 * 1024, config.buffers.read_capacity);
    assert_eq!(64 * 1024, config.buffers.tape_capacity);
    assert_eq!(8, config.buffers.shrink_factor);
    assert_eq!(16, config.buffers.shrink_hysteresis);

    assert_eq!(128, config.limits.max_nesting_depth);
    assert_eq!(512 * 1024 * 1024, config.limits.max_bulk_length);
    assert_eq!(128 * 1024 * 1024, config.limits.max_collection_length);

    assert_eq!(48, config.max_messages_per_wave);
    assert_eq!(10, SentinelConfig::default().max_discovery_rounds);
}

#[test]
fn a_default_config_validates() {
    assert!(Config::default().validate().is_ok());
}

#[test]
fn validate_rejects_knobs_whose_zero_value_would_break_the_connection() {
    // Every one of these is a divisor, a loop bound or a capacity whose zero
    // value does not degrade behaviour but removes it: no message is ever
    // flushed, no collection is ever accepted, no discovery round is ever run.
    fn assert_rejected(name: &str, zero_it: impl FnOnce(&mut Config)) {
        let mut config = Config::default();
        zero_it(&mut config);
        let error = config.validate().unwrap_err();
        assert!(
            matches!(
                error.kind(),
                ErrorKind::Client(ClientError::InvalidConfig(_))
            ),
            "{name} = 0 must be rejected"
        );
    }

    assert_rejected("read_capacity", |c| c.buffers.read_capacity = 0);
    assert_rejected("tape_capacity", |c| c.buffers.tape_capacity = 0);
    assert_rejected("shrink_factor", |c| c.buffers.shrink_factor = 0);
    assert_rejected("shrink_hysteresis", |c| c.buffers.shrink_hysteresis = 0);
    assert_rejected("max_nesting_depth", |c| c.limits.max_nesting_depth = 0);
    assert_rejected("max_bulk_length", |c| c.limits.max_bulk_length = 0);
    assert_rejected("max_collection_length", |c| {
        c.limits.max_collection_length = 0
    });
    assert_rejected("max_messages_per_wave", |c| c.max_messages_per_wave = 0);
}

#[test]
fn validate_rejects_a_zero_sentinel_discovery_round_cap() {
    // Zero rounds means discovery gives up before contacting any Sentinel.
    let mut config = Config::default();
    let mut sentinel_config = SentinelConfig {
        instances: vec![("127.0.0.1".to_owned(), 26379)],
        service_name: "myservice".to_owned(),
        ..Default::default()
    };
    sentinel_config.max_discovery_rounds = 0;
    config.server = ServerConfig::Sentinel(sentinel_config);

    let error = config.validate().unwrap_err();
    assert!(matches!(
        error.kind(),
        ErrorKind::Client(ClientError::InvalidConfig(_))
    ));
}

#[test]
fn validate_names_the_offending_knob() {
    // The error must say which knob is wrong: a config rejected at connect time
    // with an opaque message is the worst kind of startup failure.
    let mut config = Config::default();
    config.limits.max_bulk_length = 0;
    let error = config.validate().unwrap_err();
    let ErrorKind::Client(ClientError::InvalidConfig(message)) = error.kind() else {
        panic!("expected an InvalidConfig error");
    };
    assert!(
        message.contains("max_bulk_length"),
        "message did not name the knob: {message}"
    );
}

#[cfg(feature = "json")]
#[test]
fn a_config_file_sets_every_knob() {
    // A file names the knobs in the shape of the structs holding them, where a
    // URI flattens them into `backpressure.max_queued_bytes` and the like.
    let config: Config = serde_json::from_str(
        r#"{
            "server": { "Standalone": { "host": "example.com", "port": 6380 } },
            "database": 3,
            "backpressure": { "max_queued_bytes": 4096 },
            "reconnection": { "Constant": { "max_attempts": 7, "delay": 250, "jitter": 10 } }
        }"#,
    )
    .unwrap();

    assert!(matches!(
        &config.server,
        ServerConfig::Standalone { host, port } if host == "example.com" && *port == 6380
    ));
    assert_eq!(3, config.database);
    assert_eq!(4096, config.backpressure.max_queued_bytes);
    assert!(matches!(
        config.reconnection,
        ReconnectionConfig::Constant {
            max_attempts: 7,
            delay: 250,
            jitter: 10
        }
    ));
    // An absent field keeps its default rather than failing the whole file.
    assert_eq!(
        Config::default().max_messages_per_wave,
        config.max_messages_per_wave
    );
}

#[cfg(feature = "json")]
#[test]
fn a_serialized_config_round_trips() {
    let config = Config {
        connection_name: "round-trip".to_owned(),
        limits: crate::client::RespLimits {
            max_bulk_length: 1234,
            ..Default::default()
        },
        server: ServerConfig::Cluster(crate::client::ClusterConfig {
            nodes: vec![("node".to_owned(), 7000)],
            ..Default::default()
        }),
        ..Default::default()
    };

    let json = serde_json::to_string(&config).unwrap();
    let back: Config = serde_json::from_str(&json).unwrap();

    assert_eq!(config.connection_name, back.connection_name);
    assert_eq!(config.limits.max_bulk_length, back.limits.max_bulk_length);
    assert_eq!(format!("{:?}", config.server), format!("{:?}", back.server));
}

#[test]
fn the_tuning_knobs_are_addressable_in_a_uri() -> Result<()> {
    // Each key is named after the field it sets, so a URI reads like the struct
    // it builds.
    let config = "redis://127.0.0.1\
        ?buffers.read_capacity=1024\
        &buffers.tape_capacity=2048\
        &buffers.shrink_factor=4\
        &buffers.shrink_hysteresis=32\
        &backpressure.max_queued_bytes=4096\
        &backpressure.max_pubsub_bytes=8192\
        &backpressure.max_push_bytes=0\
        &limits.max_nesting_depth=16\
        &limits.max_bulk_length=1048576\
        &limits.max_collection_length=1000"
        .into_config()?;

    assert_eq!(1024, config.buffers.read_capacity);
    assert_eq!(2048, config.buffers.tape_capacity);
    assert_eq!(4, config.buffers.shrink_factor);
    assert_eq!(32, config.buffers.shrink_hysteresis);
    assert_eq!(4096, config.backpressure.max_queued_bytes);
    assert_eq!(8192, config.backpressure.max_pubsub_bytes);
    assert_eq!(0, config.backpressure.max_push_bytes);
    assert_eq!(16, config.limits.max_nesting_depth);
    assert_eq!(1048576, config.limits.max_bulk_length);
    assert_eq!(1000, config.limits.max_collection_length);

    Ok(())
}

#[test]
fn a_reconnection_policy_is_addressable_in_a_uri() -> Result<()> {
    let config = "redis://127.0.0.1?reconnection=constant".into_config()?;
    assert!(matches!(
        config.reconnection,
        ReconnectionConfig::Constant {
            max_attempts: 0,
            delay: 1000,
            jitter: 100
        }
    ));

    let config =
        "redis://127.0.0.1?reconnection=constant&reconnection.delay=250&reconnection.jitter=25&reconnection.max_attempts=3"
            .into_config()?;
    assert!(matches!(
        config.reconnection,
        ReconnectionConfig::Constant {
            max_attempts: 3,
            delay: 250,
            jitter: 25
        }
    ));

    let config =
        "redis://127.0.0.1?reconnection=linear&reconnection.delay=100&reconnection.max_delay=5000"
            .into_config()?;
    assert!(matches!(
        config.reconnection,
        ReconnectionConfig::Linear {
            max_attempts: 0,
            max_delay: 5000,
            delay: 100,
            jitter: 100
        }
    ));

    let config = "redis://127.0.0.1\
        ?reconnection=exponential\
        &reconnection.min_delay=50\
        &reconnection.max_delay=10000\
        &reconnection.multiplicative_factor=2"
        .into_config()?;
    assert!(matches!(
        config.reconnection,
        ReconnectionConfig::Exponential {
            max_attempts: 0,
            min_delay: 50,
            max_delay: 10000,
            multiplicative_factor: 2,
            jitter: 100
        }
    ));

    Ok(())
}

#[test]
fn a_reconnection_uri_that_shapes_nothing_is_rejected() {
    // `max_delay` clamps the delay, so a policy that needs one and is not given
    // it would reconnect immediately and forever. And a field belonging to
    // another policy shapes nothing at all.
    for (uri, expected) in [
        (
            "redis://127.0.0.1?reconnection=linear&reconnection.delay=100",
            "reconnection.max_delay",
        ),
        (
            "redis://127.0.0.1?reconnection=exponential&reconnection.min_delay=50&reconnection.max_delay=1000",
            "reconnection.multiplicative_factor",
        ),
        (
            "redis://127.0.0.1?reconnection=constant&reconnection.max_delay=1000",
            "reconnection.max_delay",
        ),
        (
            "redis://127.0.0.1?reconnection.delay=100",
            "reconnection.delay",
        ),
        ("redis://127.0.0.1?reconnection=quadratic", "quadratic"),
    ] {
        let error = uri.into_config().unwrap_err();
        let ErrorKind::Client(ClientError::InvalidUri(message)) = error.kind() else {
            panic!("`{uri}` should be rejected");
        };
        assert!(
            message.contains(expected),
            "`{uri}`: message `{message}` does not name `{expected}`"
        );
    }
}