1use std::{
2 borrow::Cow,
3 collections::HashMap,
4 fmt,
5 str::FromStr,
6 sync::{Arc, Mutex},
7 time::Duration,
8};
9
10use crate::{
11 errors::{Error, Result, UrlError},
12 types::{block::DEFAULT_ZSTD_LEVEL, Compression},
13};
14use percent_encoding::percent_decode;
15use url::Url;
16
17const DEFAULT_MIN_CONNS: usize = 10;
18
19const DEFAULT_MAX_CONNS: usize = 20;
20
21#[derive(Debug)]
22#[allow(clippy::large_enum_variant)]
23enum State {
24 Raw(Options),
25 Url(String),
26}
27
28#[derive(Clone)]
29pub struct OptionsSource {
30 state: Arc<Mutex<State>>,
31}
32
33impl fmt::Debug for OptionsSource {
34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35 let guard = self.state.lock().unwrap();
36 match *guard {
37 State::Url(ref url) => write!(f, "Url({url})"),
38 State::Raw(ref options) => write!(f, "{options:?}"),
39 }
40 }
41}
42
43impl OptionsSource {
44 pub(crate) fn get(&self) -> Result<Cow<'_, Options>> {
45 let mut state = self.state.lock().unwrap();
46 loop {
47 *state = match &*state {
48 State::Raw(ref options) => {
49 let ptr = options as *const Options;
50 return unsafe { Ok(Cow::Borrowed(ptr.as_ref().unwrap())) };
51 }
52 State::Url(url) => {
53 let options = from_url(url)?;
54 State::Raw(options)
55 }
56 };
57 }
58 }
59}
60
61impl Default for OptionsSource {
62 fn default() -> Self {
63 Self {
64 state: Arc::new(Mutex::new(State::Raw(Options::default()))),
65 }
66 }
67}
68
69pub trait IntoOptions {
70 fn into_options_src(self) -> OptionsSource;
71}
72
73impl IntoOptions for Options {
74 fn into_options_src(self) -> OptionsSource {
75 OptionsSource {
76 state: Arc::new(Mutex::new(State::Raw(self))),
77 }
78 }
79}
80
81impl IntoOptions for &str {
82 fn into_options_src(self) -> OptionsSource {
83 OptionsSource {
84 state: Arc::new(Mutex::new(State::Url(self.into()))),
85 }
86 }
87}
88
89impl IntoOptions for String {
90 fn into_options_src(self) -> OptionsSource {
91 OptionsSource {
92 state: Arc::new(Mutex::new(State::Url(self))),
93 }
94 }
95}
96
97#[cfg(feature = "tls-native-tls")]
99#[derive(Clone)]
100pub struct Certificate(Arc<native_tls::Certificate>);
101#[cfg(feature = "tls-native-tls")]
102impl Certificate {
103 pub fn from_der(der: &[u8]) -> Result<Certificate> {
105 let inner = match native_tls::Certificate::from_der(der) {
106 Ok(certificate) => certificate,
107 Err(err) => return Err(Error::Other(err.to_string().into())),
108 };
109 Ok(Certificate(Arc::new(inner)))
110 }
111
112 pub fn from_pem(der: &[u8]) -> Result<Certificate> {
114 let inner = match native_tls::Certificate::from_pem(der) {
115 Ok(certificate) => certificate,
116 Err(err) => return Err(Error::Other(err.to_string().into())),
117 };
118 Ok(Certificate(Arc::new(inner)))
119 }
120}
121#[cfg(feature = "tls-native-tls")]
122impl From<Certificate> for native_tls::Certificate {
123 fn from(value: Certificate) -> Self {
124 value.0.as_ref().clone()
125 }
126}
127
128#[cfg(feature = "tls-rustls")]
130#[derive(Clone)]
131pub struct Certificate(Arc<Vec<rustls::pki_types::CertificateDer<'static>>>);
132#[cfg(feature = "tls-rustls")]
133impl Certificate {
134 pub fn from_der(der: &[u8]) -> Result<Certificate> {
136 let inner = rustls::pki_types::CertificateDer::from(der.to_vec());
137 Ok(Certificate(Arc::new(vec![inner])))
138 }
139
140 pub fn from_pem(der: &[u8]) -> Result<Certificate> {
142 let mut reader = der;
143 let certs = rustls_pemfile::certs(&mut reader)
144 .collect::<std::result::Result<Vec<_>, _>>()
145 .map_err(|err| Error::Other(err.to_string().into()))?;
146 if certs.is_empty() {
147 return Err(Error::Other("no certificate found in PEM input".into()));
148 }
149 Ok(Certificate(Arc::new(certs)))
150 }
151}
152#[cfg(feature = "tls-rustls")]
153impl From<Certificate> for Vec<rustls::pki_types::CertificateDer<'static>> {
154 fn from(value: Certificate) -> Self {
155 value.0.as_ref().clone()
156 }
157}
158
159#[cfg(feature = "_tls")]
160impl fmt::Debug for Certificate {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162 write!(f, "[Certificate]")
163 }
164}
165#[cfg(feature = "_tls")]
166impl PartialEq for Certificate {
167 fn eq(&self, _other: &Self) -> bool {
168 true
169 }
170}
171
172#[derive(Clone, PartialEq, Debug)]
173pub enum SettingType {
174 String(String),
175 Bool(bool),
176 UInt64(u64),
177 Float64(f64),
178}
179
180impl fmt::Display for SettingType {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 match &self {
183 SettingType::Bool(val) => write!(f, "{val}"),
184 SettingType::UInt64(val) => write!(f, "{val}"),
185 SettingType::Float64(val) => write!(f, "{val}"),
186 SettingType::String(val) => write!(f, "{val}"),
187 }
188 }
189}
190
191impl From<&str> for SettingType {
192 fn from(val: &str) -> Self {
193 SettingType::String(val.into())
194 }
195}
196
197impl From<bool> for SettingType {
198 fn from(val: bool) -> Self {
199 SettingType::Bool(val)
200 }
201}
202
203impl From<u64> for SettingType {
204 fn from(val: u64) -> Self {
205 SettingType::UInt64(val)
206 }
207}
208
209impl From<i32> for SettingType {
210 fn from(val: i32) -> Self {
211 SettingType::UInt64(val as u64)
212 }
213}
214
215impl From<i64> for SettingType {
216 fn from(val: i64) -> Self {
217 SettingType::UInt64(val as u64)
218 }
219}
220
221impl From<f64> for SettingType {
222 fn from(val: f64) -> Self {
223 SettingType::Float64(val)
224 }
225}
226
227#[derive(Clone, PartialEq, Debug)]
228pub struct SettingValue {
229 pub(crate) value: SettingType,
230 pub(crate) is_important: bool,
231}
232impl fmt::Display for SettingValue {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 self.value.fmt(f)
235 }
236}
237
238#[derive(Clone, PartialEq)]
240pub struct Options {
241 pub(crate) addr: Url,
243
244 pub(crate) database: String,
246 pub(crate) username: String,
248 pub(crate) password: String,
250
251 pub(crate) compression: Compression,
253
254 pub(crate) pool_min: usize,
256 pub(crate) pool_max: usize,
258
259 pub(crate) nodelay: bool,
261 pub(crate) keepalive: Option<Duration>,
263
264 pub(crate) ping_before_query: bool,
266 pub(crate) send_retries: usize,
268 pub(crate) retry_timeout: Duration,
270 pub(crate) ping_timeout: Duration,
272
273 pub(crate) connection_timeout: Duration,
275
276 pub(crate) query_timeout: Duration,
278
279 pub(crate) insert_timeout: Option<Duration>,
281
282 pub(crate) execute_timeout: Option<Duration>,
284
285 #[cfg(feature = "_tls")]
287 pub(crate) secure: bool,
288
289 #[cfg(feature = "_tls")]
291 pub(crate) skip_verify: bool,
292
293 #[cfg(feature = "_tls")]
295 pub(crate) certificate: Option<Certificate>,
296
297 pub(crate) settings: HashMap<String, SettingValue>,
299
300 pub(crate) alt_hosts: Vec<Url>,
302}
303
304impl fmt::Debug for Options {
305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
306 f.debug_struct("Options")
307 .field("addr", &self.addr)
308 .field("database", &self.database)
309 .field("compression", &self.compression)
310 .field("pool_min", &self.pool_min)
311 .field("pool_max", &self.pool_max)
312 .field("nodelay", &self.nodelay)
313 .field("keepalive", &self.keepalive)
314 .field("ping_before_query", &self.ping_before_query)
315 .field("send_retries", &self.send_retries)
316 .field("retry_timeout", &self.retry_timeout)
317 .field("ping_timeout", &self.ping_timeout)
318 .field("connection_timeout", &self.connection_timeout)
319 .field("settings", &self.settings)
320 .field("alt_hosts", &self.alt_hosts)
321 .finish()
322 }
323}
324
325impl Default for Options {
326 fn default() -> Self {
327 Self {
328 addr: Url::parse("tcp://default@127.0.0.1:9000").unwrap(),
329 database: "default".into(),
330 username: "default".into(),
331 password: "".into(),
332 compression: Compression::None,
333 pool_min: DEFAULT_MIN_CONNS,
334 pool_max: DEFAULT_MAX_CONNS,
335 nodelay: true,
336 keepalive: None,
337 ping_before_query: true,
338 send_retries: 3,
339 retry_timeout: Duration::from_secs(5),
340 ping_timeout: Duration::from_millis(500),
341 connection_timeout: Duration::from_millis(500),
342 query_timeout: Duration::from_secs(180),
343 insert_timeout: Some(Duration::from_secs(180)),
344 execute_timeout: Some(Duration::from_secs(180)),
345 #[cfg(feature = "_tls")]
346 secure: false,
347 #[cfg(feature = "_tls")]
348 skip_verify: false,
349 #[cfg(feature = "_tls")]
350 certificate: None,
351 settings: HashMap::new(),
352 alt_hosts: Vec::new(),
353 }
354 }
355}
356
357macro_rules! property {
358 ( $k:ident: $t:ty ) => {
359 pub fn $k(self, $k: $t) -> Self {
360 Self {
361 $k: $k.into(),
362 ..self
363 }
364 }
365 };
366 ( $(#[$attr:meta])* => $k:ident: $t:ty ) => {
367 $(#[$attr])*
368 pub fn $k(self, $k: $t) -> Self {
369 Self {
370 $k: $k.into(),
371 ..self
372 }
373 }
374 }
375}
376
377impl Options {
378 pub fn new<A>(addr: A) -> Self
380 where
381 A: Into<Url>,
382 {
383 Self {
384 addr: addr.into(),
385 ..Self::default()
386 }
387 }
388
389 pub(crate) fn zstd_level(&self) -> i32 {
394 let level = self
395 .settings
396 .get("network_zstd_compression_level")
397 .and_then(|setting| match &setting.value {
398 SettingType::String(value) => value.trim().parse::<i32>().ok(),
399 SettingType::UInt64(value) => i32::try_from(*value).ok(),
400 SettingType::Float64(value) if value.is_finite() && value.fract() == 0.0 => {
401 Some(*value as i32)
402 }
403 SettingType::Float64(_) | SettingType::Bool(_) => None,
404 });
405 match level {
406 Some(level) if (1..=22).contains(&level) => level,
407 _ => DEFAULT_ZSTD_LEVEL,
408 }
409 }
410
411 pub fn with_setting<V>(mut self, name: &str, value: V, is_important: bool) -> Self
412 where
413 V: Into<SettingType>,
414 {
415 let value: SettingType = value.into();
416 self.settings.insert(
417 name.into(),
418 SettingValue {
419 value,
420 is_important,
421 },
422 );
423 self
424 }
425
426 property! {
427 => database: &str
429 }
430
431 property! {
432 => username: &str
434 }
435
436 property! {
437 => password: &str
439 }
440
441 pub fn with_compression(self) -> Self {
443 Self {
444 compression: Compression::Lz4,
445 ..self
446 }
447 }
448
449 property! {
450 => compression: Compression
455 }
456
457 property! {
458 => pool_min: usize
460 }
461
462 property! {
463 => pool_max: usize
465 }
466
467 property! {
468 => nodelay: bool
470 }
471
472 property! {
473 => keepalive: Option<Duration>
475 }
476
477 property! {
478 => ping_before_query: bool
480 }
481
482 property! {
483 => send_retries: usize
485 }
486
487 property! {
488 => retry_timeout: Duration
490 }
491
492 property! {
493 => ping_timeout: Duration
495 }
496
497 property! {
498 => connection_timeout: Duration
500 }
501
502 property! {
503 => query_timeout: Duration
505 }
506
507 property! {
508 => insert_timeout: Option<Duration>
510 }
511
512 property! {
513 => execute_timeout: Option<Duration>
515 }
516
517 #[cfg(feature = "_tls")]
518 property! {
519 => secure: bool
521 }
522
523 #[cfg(feature = "_tls")]
524 property! {
525 => skip_verify: bool
527 }
528
529 #[cfg(feature = "_tls")]
530 property! {
531 => certificate: Option<Certificate>
533 }
534
535 property! {
536 => settings: HashMap<String, SettingValue>
538 }
539
540 property! {
541 => alt_hosts: Vec<Url>
543 }
544}
545
546impl FromStr for Options {
547 type Err = Error;
548
549 fn from_str(url: &str) -> Result<Self> {
550 from_url(url)
551 }
552}
553
554fn from_url(url_str: &str) -> Result<Options> {
555 let url = Url::parse(url_str)?;
556
557 if url.scheme() != "tcp" {
558 return Err(UrlError::UnsupportedScheme {
559 scheme: url.scheme().to_string(),
560 }
561 .into());
562 }
563
564 if url.cannot_be_a_base() || !url.has_host() {
565 return Err(UrlError::Invalid.into());
566 }
567
568 let mut options = Options::default();
569
570 if let Some(username) = get_username_from_url(&url) {
571 options.username = username.into();
572 }
573
574 if let Some(password) = get_password_from_url(&url) {
575 options.password = password.into()
576 }
577
578 let mut addr = url.clone();
579 addr.set_path("");
580 addr.set_query(None);
581
582 let port = url.port().or(Some(9000));
583 addr.set_port(port).map_err(|_| UrlError::Invalid)?;
584 options.addr = addr;
585
586 if let Some(database) = get_database_from_url(&url)? {
587 options.database = database.into();
588 }
589
590 set_params(&mut options, url.query_pairs())?;
591
592 Ok(options)
593}
594
595fn set_params<'a, I>(options: &mut Options, iter: I) -> std::result::Result<(), UrlError>
596where
597 I: Iterator<Item = (Cow<'a, str>, Cow<'a, str>)>,
598{
599 for (key, value) in iter {
600 match key.as_ref() {
601 "pool_min" => options.pool_min = parse_param(key, value, usize::from_str)?,
602 "pool_max" => options.pool_max = parse_param(key, value, usize::from_str)?,
603 "nodelay" => options.nodelay = parse_param(key, value, bool::from_str)?,
604 "keepalive" => options.keepalive = parse_param(key, value, parse_opt_duration)?,
605 "ping_before_query" => {
606 options.ping_before_query = parse_param(key, value, bool::from_str)?
607 }
608 "send_retries" => options.send_retries = parse_param(key, value, usize::from_str)?,
609 "retry_timeout" => options.retry_timeout = parse_param(key, value, parse_duration)?,
610 "ping_timeout" => options.ping_timeout = parse_param(key, value, parse_duration)?,
611 "connection_timeout" => {
612 options.connection_timeout = parse_param(key, value, parse_duration)?
613 }
614 "query_timeout" => options.query_timeout = parse_param(key, value, parse_duration)?,
615 "insert_timeout" => {
616 options.insert_timeout = parse_param(key, value, parse_opt_duration)?
617 }
618 "execute_timeout" => {
619 options.execute_timeout = parse_param(key, value, parse_opt_duration)?
620 }
621 "compression" => options.compression = parse_param(key, value, parse_compression)?,
622 #[cfg(feature = "_tls")]
623 "secure" => options.secure = parse_param(key, value, bool::from_str)?,
624 #[cfg(feature = "_tls")]
625 "skip_verify" => options.skip_verify = parse_param(key, value, bool::from_str)?,
626 "alt_hosts" => options.alt_hosts = parse_param(key, value, parse_hosts)?,
627 _ => {
628 let value = SettingType::String(value.to_string());
629 options.settings.insert(
630 key.to_string(),
631 SettingValue {
632 value,
633 is_important: true,
634 },
635 );
636 }
637 };
638 }
639
640 Ok(())
641}
642
643fn parse_param<'a, F, T, E>(
644 param: Cow<'a, str>,
645 value: Cow<'a, str>,
646 parse: F,
647) -> std::result::Result<T, UrlError>
648where
649 F: Fn(&str) -> std::result::Result<T, E>,
650{
651 let source = percent_decode(value.as_bytes()).decode_utf8_lossy();
652 match parse(source.as_ref()) {
653 Ok(value) => Ok(value),
654 Err(_) => Err(UrlError::InvalidParamValue {
655 param: param.into(),
656 value: value.into(),
657 }),
658 }
659}
660
661fn get_username_from_url(url: &Url) -> Option<Cow<'_, str>> {
662 let user = url.username();
663 if user.is_empty() {
664 return None;
665 }
666 Some(percent_decode(user.as_bytes()).decode_utf8_lossy())
667}
668
669fn get_password_from_url(url: &Url) -> Option<Cow<'_, str>> {
670 let password = url.password()?;
671 Some(percent_decode(password.as_bytes()).decode_utf8_lossy())
672}
673
674fn get_database_from_url(url: &Url) -> Result<Option<&str>> {
675 match url.path_segments() {
676 None => Ok(None),
677 Some(mut segments) => {
678 let head = segments.next();
679
680 if segments.next().is_some() {
681 return Err(Error::Url(UrlError::Invalid));
682 }
683
684 match head {
685 Some(database) if !database.is_empty() => Ok(Some(database)),
686 _ => Ok(None),
687 }
688 }
689 }
690}
691
692fn parse_duration(source: &str) -> std::result::Result<Duration, ()> {
693 let digits_count = source.chars().take_while(|c| c.is_ascii_digit()).count();
694
695 let left: String = source.chars().take(digits_count).collect();
696 let right: String = source.chars().skip(digits_count).collect();
697
698 let num = match u64::from_str(&left) {
699 Ok(value) => value,
700 Err(_) => return Err(()),
701 };
702
703 match right.as_str() {
704 "s" => Ok(Duration::from_secs(num)),
705 "ms" => Ok(Duration::from_millis(num)),
706 _ => Err(()),
707 }
708}
709
710fn parse_opt_duration(source: &str) -> std::result::Result<Option<Duration>, ()> {
711 if source == "none" {
712 return Ok(None);
713 }
714
715 let duration = parse_duration(source)?;
716 Ok(Some(duration))
717}
718
719fn parse_compression(source: &str) -> Result<Compression> {
720 Compression::from_str(source)
721}
722
723fn parse_hosts(source: &str) -> std::result::Result<Vec<Url>, ()> {
724 let mut result = Vec::new();
725 for host in source.split(',') {
726 match Url::from_str(&format!("tcp://{host}")) {
727 Ok(url) => result.push(url),
728 Err(_) => return Err(()),
729 }
730 }
731 Ok(result)
732}
733
734#[cfg(test)]
735mod test {
736 use super::*;
737
738 #[test]
739 fn test_parse_hosts() {
740 let source = "host2:9000,host3:9000";
741 let expected = vec![
742 Url::from_str("tcp://host2:9000").unwrap(),
743 Url::from_str("tcp://host3:9000").unwrap(),
744 ];
745 let actual = parse_hosts(source).unwrap();
746 assert_eq!(actual, expected)
747 }
748
749 #[test]
750 fn test_parse_default() {
751 let url = "tcp://host1";
752 let options = from_url(url).unwrap();
753 assert_eq!(options.database, "default");
754 assert_eq!(options.username, "default");
755 assert_eq!(options.password, "");
756 }
757
758 #[test]
759 #[cfg(feature = "_tls")]
760 fn test_parse_secure_options() {
761 let url = "tcp://username:password@host1:9001/database?ping_timeout=42ms&keepalive=99s&compression=lz4&connection_timeout=10s&secure=true&skip_verify=true";
762 assert_eq!(
763 Options {
764 username: "username".into(),
765 password: "password".into(),
766 addr: Url::parse("tcp://username:password@host1:9001").unwrap(),
767 database: "database".into(),
768 keepalive: Some(Duration::from_secs(99)),
769 ping_timeout: Duration::from_millis(42),
770 connection_timeout: Duration::from_secs(10),
771 compression: Compression::Lz4,
772 secure: true,
773 skip_verify: true,
774 ..Options::default()
775 },
776 from_url(url).unwrap(),
777 );
778 }
779
780 #[test]
781 fn test_parse_encoded_creds() {
782 let url = "tcp://user%20%3Cbar%3E:password%20%3Cbar%3E@host1:9001/database?ping_timeout=42ms&keepalive=99s&compression=lz4&connection_timeout=10s";
783 assert_eq!(
784 Options {
785 username: "user <bar>".into(),
786 password: "password <bar>".into(),
787 addr: Url::parse("tcp://user%20%3Cbar%3E:password%20%3Cbar%3E@host1:9001").unwrap(),
788 database: "database".into(),
789 keepalive: Some(Duration::from_secs(99)),
790 ping_timeout: Duration::from_millis(42),
791 connection_timeout: Duration::from_secs(10),
792 compression: Compression::Lz4,
793 ..Options::default()
794 },
795 from_url(url).unwrap(),
796 );
797 }
798
799 #[test]
800 fn test_parse_options() {
801 let url = "tcp://username:password@host1:9001/database?ping_timeout=42ms&keepalive=99s&compression=lz4&connection_timeout=10s";
802 assert_eq!(
803 Options {
804 username: "username".into(),
805 password: "password".into(),
806 addr: Url::parse("tcp://username:password@host1:9001").unwrap(),
807 database: "database".into(),
808 keepalive: Some(Duration::from_secs(99)),
809 ping_timeout: Duration::from_millis(42),
810 connection_timeout: Duration::from_secs(10),
811 compression: Compression::Lz4,
812 ..Options::default()
813 },
814 from_url(url).unwrap(),
815 );
816 }
817
818 #[test]
819 #[should_panic]
820 fn test_parse_invalid_url() {
821 let url = "ʘ_ʘ";
822 from_url(url).unwrap();
823 }
824
825 #[test]
826 fn test_parse_with_unknown_setting() {
827 let url = "tcp://localhost:9000/foo?bar=baz";
828 assert_eq!(
829 Options {
830 addr: Url::parse("tcp://localhost:9000").unwrap(),
831 database: "foo".into(),
832 settings: HashMap::from([(
833 "bar".into(),
834 SettingValue {
835 value: SettingType::String("baz".into()),
836 is_important: true,
837 }
838 ),]),
839 ..Options::default()
840 },
841 from_url(url).unwrap(),
842 );
843 }
845
846 #[test]
847 fn test_with_setting() {
848 {
849 let opts = Options::from_str("tcp://localhost:9000")
850 .unwrap()
851 .with_setting("foo", "bar", true);
852 assert_eq!(
853 opts.settings,
854 HashMap::from([(
855 "foo".into(),
856 SettingValue {
857 value: SettingType::String("bar".into()),
858 is_important: true,
859 }
860 )])
861 );
862 }
863
864 {
865 let opts = Options::from_str("tcp://localhost:9000")
866 .unwrap()
867 .with_setting("foo", "bar", false);
868 assert_eq!(
869 opts.settings,
870 HashMap::from([(
871 "foo".into(),
872 SettingValue {
873 value: SettingType::String("bar".into()),
874 is_important: false,
875 }
876 )])
877 );
878 }
879
880 {
881 let opts = Options::from_str("tcp://localhost:9000")
882 .unwrap()
883 .with_setting("foo", 1, true);
884 assert_eq!(
885 opts.settings,
886 HashMap::from([(
887 "foo".into(),
888 SettingValue {
889 value: SettingType::UInt64(1u64),
890 is_important: true,
891 }
892 )])
893 );
894 }
895
896 {
897 let opts = Options::from_str("tcp://localhost:9000")
898 .unwrap()
899 .with_setting("foo", true, true);
900 assert_eq!(
901 opts.settings,
902 HashMap::from([(
903 "foo".into(),
904 SettingValue {
905 value: SettingType::Bool(true),
906 is_important: true,
907 }
908 )])
909 );
910 }
911
912 {
913 let opts = Options::from_str("tcp://localhost:9000")
914 .unwrap()
915 .with_setting("foo", 1., true);
916 assert_eq!(
917 opts.settings,
918 HashMap::from([(
919 "foo".into(),
920 SettingValue {
921 value: SettingType::Float64(1.),
922 is_important: true,
923 }
924 )])
925 );
926 }
927 }
928
929 #[test]
930 #[should_panic]
931 fn test_parse_with_multi_databases() {
932 let url = "tcp://localhost:9000/foo/bar";
933 from_url(url).unwrap();
934 }
935
936 #[test]
937 fn test_parse_duration() {
938 assert_eq!(parse_duration("3s").unwrap(), Duration::from_secs(3));
939 assert_eq!(parse_duration("123ms").unwrap(), Duration::from_millis(123));
940
941 parse_duration("ms").unwrap_err();
942 parse_duration("1ss").unwrap_err();
943 }
944
945 #[test]
946 fn test_parse_opt_duration() {
947 assert_eq!(
948 parse_opt_duration("3s").unwrap(),
949 Some(Duration::from_secs(3))
950 );
951 assert_eq!(parse_opt_duration("none").unwrap(), None::<Duration>);
952 }
953
954 #[test]
955 fn test_parse_compression() {
956 assert_eq!(parse_compression("none").unwrap(), Compression::None);
957 assert_eq!(parse_compression("lz4").unwrap(), Compression::Lz4);
958 assert_eq!(parse_compression("zstd").unwrap(), Compression::Zstd);
959 parse_compression("?").unwrap_err();
960
961 let options = from_url("tcp://localhost?compression=zstd").unwrap();
962 assert_eq!(options.compression, Compression::Zstd);
963 from_url("tcp://localhost?compression=brotli").unwrap_err();
964 }
965
966 #[test]
967 fn test_zstd_level() {
968 let level = |url: &str| from_url(url).unwrap().zstd_level();
969 assert_eq!(level("tcp://localhost?compression=zstd"), 3);
970 assert_eq!(
971 level("tcp://localhost?compression=zstd&network_zstd_compression_level=1"),
972 1
973 );
974 assert_eq!(level("tcp://localhost?network_zstd_compression_level=9"), 9);
975 assert_eq!(level("tcp://localhost?network_zstd_compression_level=0"), 3);
976 assert_eq!(level("tcp://localhost?network_zstd_compression_level=x"), 3);
977
978 let with = |value: SettingType| {
979 Options::default()
980 .with_setting("network_zstd_compression_level", value, true)
981 .zstd_level()
982 };
983 assert_eq!(with(SettingType::UInt64(5)), 5);
984 assert_eq!(with(SettingType::Float64(9.0)), 9);
985 assert_eq!(with(SettingType::Float64(2.5)), 3);
986 assert_eq!(with(SettingType::Bool(true)), 3);
987 }
988
989 #[cfg(feature = "tls-rustls")]
990 #[test]
991 fn test_certificate_from_pem_without_certificates() {
992 Certificate::from_pem(b"").unwrap_err();
993 let key_only = b"-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n";
994 Certificate::from_pem(key_only).unwrap_err();
995 }
996}